<template>
	<div class="system-systemUserdmin-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1300px">
			<el-card shadow="hover">
				<el-form :model="state.ruleForm" ref="datainterfaceDialogFormRef" :rules="rules" size="default" label-width="120px">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="用户名" prop="userName">
								<el-input :disabled.sync="state.dialog.type === 'edit'" v-model="state.ruleForm.userName" placeholder="用户名" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="密码" prop="password">
								<el-input show-password v-model="state.ruleForm.password" placeholder="密码" clearable
									:disabled.sync="state.dialog.type === 'edit'"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="邮箱" prop="email">
								<el-input v-model="state.ruleForm.email" placeholder="邮箱" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="全名" prop="fullName">
								<el-input v-model="state.ruleForm.fullName" placeholder="全名" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="默认角色" prop="defaultRole">
								<el-input v-model="state.ruleForm.defaultRole" placeholder="defaultRole" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="用户类型" prop="userType">
								<el-select v-if="state.dialog.title != '修改用户'" v-model="state.ruleForm.userType" placeholder="用户类型" class="input-width" style="width: 100%">
									<el-option v-for="item in state.createUserTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>

								<dicItemsETag v-if="state.dialog.title == '修改用户'" dicCode="userType" :value="state.ruleForm.userType" :key="state.ruleForm.userType" />

								<!-- <el-input v-model="state.ruleForm.userType" placeholder="userType" clearable></el-input> -->
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="userRegistSource" prop="userRegistSource">
								<el-input v-model="state.ruleForm.userRegistSource" placeholder="userRegistSource"
									clearable></el-input>
							</el-form-item>
						</el-col> -->
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="手机号" prop="mobilePhone">
								<el-input v-model="state.ruleForm.mobilePhone" placeholder="手机号" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="状态" prop="status">
								<el-select clearable v-model.number="state.ruleForm.status">
									<el-option v-for="item in state.statusList" :key="item.dicItemValue" :label="item.dicItemName" :value="parseInt(item.dicItemValue)" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-card>


			<el-card style="margin-top: 20px;" shadow="hover">
				<el-row>
					<el-col :span="9" class="mb20">
						<el-card shadow="hover">
							<el-form>
								<el-row :gutter="10">
									<el-col :span="20">
										<el-form-item label="关键字:">
											<el-input clearable size="default" v-model="state.keyWord" placeholder="关键字模糊查询，可按列表字段模糊查询"></el-input>
										</el-form-item>
									</el-col>
									<el-col :span="4">
										<el-button style="margin-top: 4px;" type="primary" size="default" @click="filterBtn">过滤</el-button>
									</el-col>
								</el-row>
							</el-form>
						</el-card>
						<el-table size="default" :data="state.sysRoleAll.list" @selection-change="handleSelectionChange1" style="width: 100%">
							<el-table-column type="selection" width="45"></el-table-column>
							<el-table-column label="roleCode" prop="roleCode"></el-table-column>
							<el-table-column label="roleName" prop="roleName"></el-table-column>
						</el-table>
					</el-col>
					<el-col :span="2" class="mb20">
						<div class="alig_container">
							<div>
								<el-button type="primary" size="default" @click="leftToRight"> {{ '>' }} </el-button>
							</div>
							<div>
								<el-button type="primary" size="default" @click="rightToLeft"> {{ '<' }} </el-button>
							</div>
						</div>
					</el-col>
					<el-col :span="13" class="mb20">
						<el-table size="default" :data="state.userRoleList" @selection-change="handleSelectionChange2" style="width: 100%">
							<el-table-column type="selection" width="45"></el-table-column>
							<!-- <el-table-column label="序号">
								<template #default="scope">{{ scope.row.index = scope.$index + 1 }}</template>
							</el-table-column> -->
							<el-table-column label="roleCode" prop="roleCode"></el-table-column>
							<el-table-column label="roleName" prop="roleName"></el-table-column>
							<el-table-column label="有效期">
								<template #default="scope">
									<el-form :model="scope.row" :inline="true">
										<el-form-item prop="validatorStart">
											<el-date-picker v-model="scope.row.validatorStart" type="date" placeholder="开始日期" size="default"
												:style="{ width: '150px' }"></el-date-picker>
										</el-form-item>
										<el-form-item prop="validatorEnd">
											<el-date-picker v-model="scope.row.validatorEnd" type="date" placeholder="结束日期" size="default"
												:style="{ width: '150px' }"></el-date-picker>
										</el-form-item>
									</el-form>
								</template>
							</el-table-column>
						</el-table>
					</el-col>
				</el-row>
			</el-card>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script setup lang="ts" name="systemDicDialog">
import { ElMessage } from 'element-plus';
import { reactive, ref, watch,defineAsyncComponent } from 'vue';
// 导入接口
import { useSysApi } from "../../../api/sys";
const datainterfaceDialogFormRef = ref();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const dicItemsETag = defineAsyncComponent(() => import('/@/components/dic/dicItemsETag.vue'));

const rules = {
	userName: [
		{
			required: true,
			message: "不能为空，请重新输入！",
			trigger: "blur"
		},
		{ min: 2, max: 50, message: "长度在2到50个字符", trigger: "blur" }
	],
	password: [
		{
			required: true,
			message: "不能为空，请重新输入！",
			trigger: "blur"
		},
		{ min: 6, max: 50, message: "长度在6到50个字符", trigger: "blur" }
	],
	defaultRole: [
		{
			required: true,
			message: "不能为空，请重新输入！",
			trigger: "blur"
		}
	],
	userType: [
		{
			required: true,
			message: "不能为空，请重新输入！",
			trigger: "blur"
		}
	],
	userRegistSource: [
		{
			required: true,
			message: "不能为空，请重新输入！",
			trigger: "blur"
		}
	],
	status: [
		{
			required: true,
			message: "不能为空，请重新输入！",
			trigger: "blur"
		}
	]
}

const state = reactive({
	keyWord: "",
	userRoleList: [] as any,
	createUserTypeList: [
		{
			label: "后台管理用户",
			value: "admin",
		},
		{
			label: "虚拟用户",
			value: "virtual",
		}
	],
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	id: "",
	ruleForm: {
		password: "",
		userName: "",
		email: "",
		fullName: "",
		defaultRole: "",
		userType: "admin",
		userRegistSource: "",
		mobilePhone: "",
		status: ""

	} as any,
	statusList: [] as any,
	sysRoleAll: {
		page: 1,
		limit: 50,
		total: 0,
		list: [],
		multipleSelection1: [],
		multipleSelection2: [],
		roleQueryParms: {
			params: {},
			sorts: "role_code,role_name"
		}
	},


	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});


// 打开弹窗
const openDialog = async (type: string, row?: any) => {
	if (type === 'edit') {
		state.id = row.id;
		state.ruleForm = {
			password: row.password,
			userName: row.userName,
			email: row.email,
			fullName: row.fullName,
			defaultRole: row.defaultRole,
			userType: row.userType,
			userRegistSource: row.userRegistSource,
			mobilePhone: row.mobilePhone,
			status: row.status
		}
		state.userRoleList = [];
		state.userRoleList = await useSysApi().queryDynamicSqlList("fbf2e7c0ec6c91d9041ccd92509ce309", {
			params: { userId: row.id },
			sorts: "r.role_Code,R.role_name"
		});
		state.dialog.title = '修改用户';
		state.dialog.submitTxt = '修 改';
	} else {
		state.id = "";
		state.ruleForm = {
			password: "",
			userName: "",
			email: "",
			fullName: "",
			defaultRole: "User",
			userType: "admin",
			userRegistSource: "background",
			mobilePhone: "",
			status: 2
		}
		state.dialog.title = '新增用户';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};


// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {



	// 检查顶层表单
	datainterfaceDialogFormRef.value.validate(async (valid: any) => {
		if (valid) {
			//检查参数列表

			let vo = {
				defaultRole: state.ruleForm.defaultRole,
				status: state.ruleForm.status,
				updated: false,
				userName: state.ruleForm.userName,
				password: state.ruleForm.password,
				email: state.ruleForm.email,
				fullName: state.ruleForm.fullName,
				mobilePhone: state.ruleForm.mobilePhone,
				userRegistSource: state.ruleForm.userRegistSource,
				userType: state.ruleForm.userType
			} as any;

			vo["frameUserRoleList"] = state.userRoleList;
			if (state.dialog.type == 'edit') {
				vo.updated = true;
				vo["id"] = state.id;
			}

			try {
				await useSysApi().saveOrUpdateFrameUser(vo);
				ElMessage.success("操作成功");
				closeDialog(); // 关闭弹窗
				emit('refresh');
			} catch (error) {
				ElMessage.error("操作失败请稍后再试");
			}





		} else {
			ElMessage.warning("请检查数据的正确性！");
		}
	})







	// closeDialog(); // 关闭弹窗
	// emit('refresh');
	// if (state.dialog.type === 'add') { }
	// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};




const selectDicItemsByDicCode = async () => {
	state.statusList = await useSysApi().selectDicItemsByDicCode("userStatus", "COMMON-SERVICE");
}

const allRolesQuery = async () => {
	const vo = {
		params: {},
		sorts: state.sysRoleAll.roleQueryParms.sorts
	}
	if (state.keyWord) vo["params"]['keyWord'] = state.keyWord;
	let temp = await useSysApi().queryDynamicSqlPaged("fca0c2236325f81017b12e4da4d32990", state.sysRoleAll.page, state.sysRoleAll.limit, vo);
	state.sysRoleAll.total = temp.total;
	// 得到list 然后跟右侧对比


	state.sysRoleAll.list = temp.list;
}

const filterBtn = () => {
	allRolesQuery();
}

// 分页改变
const onHandleSizeChange1 = (val: number) => {
	state.sysRoleAll.limit = val;
	allRolesQuery();
};
// 分页改变
const onHandleCurrentChange1 = (val: number) => {
	state.sysRoleAll.page = val;
	allRolesQuery();
};


const handleSelectionChange1 = (val: any) => {
	state.sysRoleAll.multipleSelection1 = val;
}

const handleSelectionChange2 = (val: any) => {
	state.sysRoleAll.multipleSelection2 = val;
}

const leftToRight = () => {
	if (state.sysRoleAll.multipleSelection1.length <= 0) return;
	const listTemp = [] as any;
	state.sysRoleAll.multipleSelection1.map((x: any) => {
		let indexR = state.userRoleList.findIndex((y: any) => y.roleCode == x.roleCode);
		if (indexR < 0) {
			let now = new Date();
			listTemp.push(Object.assign(x, {
				validatorEnd: new Date(now.setFullYear(now.getFullYear() + 1)),
				validatorStart: new Date()
			}));
		}
	})
	state.userRoleList.push(...listTemp);
}


const rightToLeft = () => {
	if (state.sysRoleAll.multipleSelection2.length <= 0) return;
	let remp = state.userRoleList.filter((x: any) => {
		let rs = state.sysRoleAll.multipleSelection2.some((b: any) => {
			return b.roleCode == x.roleCode;
		})
		return !rs;
	})
	state.userRoleList = remp;
}



watch(
	() => state.dialog.isShowDialog,
	(newValue) => {
		if (newValue == true) {
			selectDicItemsByDicCode();
			// 查询角色列表
			allRolesQuery();
		}
	}, { immediate: true }
);




// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss">
.el-select {
	width: 100% !important;
}



.system-systemUserdmin-dialog-container {
	.bar_tools {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.el-table__expanded-cell {
		padding: 20px;
	}


	.alig_container {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;

		&>div {
			margin: 15px 0px;
			display: flex;
			justify-content: center;
		}
	}
}
</style>